package edu.chl.food_store.utility;

import java.security.NoSuchProviderException;
import java.util.Properties;
import javax.mail.*;
import javax.mail.internet.*;

/**
 * Simple mailer that sends an e-mail with the given context to a given
 * address.
 * 
 * Note: Class uses a registered Google Mail account, do not use this account
 * for sending abusive e-mail messages!
 */
public class Mailer {

    public static void sendMail(String messageString, String emailAddress) throws NoSuchProviderException, MessagingException {
        //Set up mail
        String SMTP_HOST_NAME = "smtp.gmail.com";
        int SMTP_HOST_PORT = 465;
        String SMTP_AUTH_USER = "orderconfirmation.bwa@gmail.com";
        String SMTP_AUTH_PWD = "chalmers123";
        String RECEIVER = emailAddress;
        Properties properties = new Properties();
        properties.put("mail.transport.protocol", "smtps");
        properties.put("mail.smtps.host", SMTP_HOST_NAME);
        properties.put("mail.smtps.auth", "true");
        Session mailSession = Session.getDefaultInstance(properties);
        mailSession.setDebug(true);
        Transport transport = mailSession.getTransport();
        MimeMessage mailMessage = new MimeMessage(mailSession);
        mailMessage.setSubject("Order");
        mailMessage.setContent(messageString, "text/plain");
        mailMessage.addRecipient(Message.RecipientType.TO, new InternetAddress(RECEIVER));
        //Connect
        transport.connect(SMTP_HOST_NAME, SMTP_HOST_PORT, SMTP_AUTH_USER, SMTP_AUTH_PWD);
        //Send mail
        transport.sendMessage(mailMessage, mailMessage.getRecipients(Message.RecipientType.TO));
        transport.close();
    }
}
